package cqrtplm.service.impl;



import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import cqrtplm.client.SapApiClient;
import cqrtplm.constant.IpAddressConstant;
import cqrtplm.dto.SAPSupplierDTO;
import cqrtplm.dto.SAPSupplierRequestDTO;
import cqrtplm.dto.SAPSupplierResponseDTO;
import cqrtplm.dto.thirdPartyAPI.*;
import cqrtplm.service.SapApiService;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


@Service
public class SapApiServiceImpl implements SapApiService {

    private final SapApiClient sapApiClient;

    public SapApiServiceImpl(SapApiClient sapApiClient) {
        this.sapApiClient = sapApiClient;
    }

    @Override
    public Map<String,SAPSupplierDTO> getSAPSupplier(String factoryId, String drawingCode) {
        String endpoint="DSPF/SI_ZMM_DSPF2SAP_SOURCESLCT_SREQ";
            try {
                // 创建主DTO对象
                SAPSupplierRequestDTO requestDTO = new SAPSupplierRequestDTO();

                // 创建内部列表对象
                SAPSupplierRequestDTO.SAPSupplierRequestItemList itemList =
                        new SAPSupplierRequestDTO.SAPSupplierRequestItemList();

                // 创建并设置项目数据
                SAPSupplierRequestDTO.SAPSupplierRequestItem item =
                        new SAPSupplierRequestDTO.SAPSupplierRequestItem();

                item.setMATNR(drawingCode);
                item.setWERKS(factoryId);
                // 其他字段保持null

                // 设置项目数组
                itemList.setItem(new SAPSupplierRequestDTO.SAPSupplierRequestItem[]{item});

                // 设置主DTO的内部列表
                requestDTO.setItTab(itemList);

                // 配置ObjectMapper以忽略null值
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

                // 序列化为JSON字符串
                String jsonPayload = objectMapper.writeValueAsString(requestDTO);

                // 2. 调用API
                String retstring=sapApiClient.callSapApi(factoryId, endpoint, jsonPayload);

                //返回json处理成对象
                SAPSupplierResponseDTO ret=objectMapper.readValue(retstring,
                                                                  new TypeReference<SAPSupplierResponseDTO>(){});

                Map<String,SAPSupplierDTO> supplierMap=new HashMap<>();
                //遍历返回对象并创建供应商对象
                for (SAPSupplierResponseDTO.SAPSupplierResponseItem retItem : ret.getEtTab().getItem()) {
                    // 检查关键属性是否存在
                    if (retItem.getLIFNR() != null && !retItem.getLIFNR().isEmpty()) {
                        // 创建供应商DTO并映射属性
                        SAPSupplierDTO supplierDTO = new SAPSupplierDTO();
                        supplierDTO.setDrawingCode(drawingCode);
                        supplierDTO.setFactory(retItem.getWERKS());
                        supplierDTO.setCode(retItem.getLIFNR());                // LIFNR -> code
                        supplierDTO.setShortName(retItem.getBU_SORT1());       // BU_SORT1 -> shortName
                        supplierDTO.setFullName(retItem.getNAME_ORG1());       // NAME_ORG1 -> fullName
                        // 存入Map会自动去重（相同LIFNR的记录会被覆盖）
                        supplierMap.put(retItem.getLIFNR(), supplierDTO);
                    }
                }
                return supplierMap;

            } catch (JsonProcessingException e) {
                // 使用 RuntimeException 包装，保留原始堆栈信息
                throw new RuntimeException("JSON解析失败", e);
            }
    }

    //    @Override
//    public <T> T getMaterialStock(String factoryId, String materialId, Class<T> responseType) {
//        MaterialStockRequest request = new MaterialStockRequest(materialId);
//        return null;
//    }
//
//    // 请求对象类
//    private static class MaterialStockRequest {
//        private final String materialId;
//
//        public MaterialStockRequest(String materialId) {
//            this.materialId = materialId;
//        }
//
//        public String getMaterialId() {
//            return materialId;
//        }
//    }


    @Override
    public RestAdapterWlDTO restAdapterWl(RestAdapterWlDTO dto) {

        // 生成Basic认证字符串
        String username = IpAddressConstant.USER_CS;
        String password = IpAddressConstant.PASSWORD_CS;
        String auth = username + ":" + password;
        String base64Auth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        String authHeader = "Basic " + base64Auth;

        String body = HttpRequest.post(IpAddressConstant.SAP_CS_WLDR)
                .header("Content-Type", "application/json")
                .header("Authorization", authHeader)  // 添加Basic认证头
                .body(JSONUtil.toJsonStr(dto))
                .execute()
                .body();

        RestAdapterWlDTO restAdapterDTO = JSONUtil.toBean(body, RestAdapterWlDTO.class);

        return restAdapterDTO;
    }

    @Override
    public RestAdapterBomDTO restAdapterBom(RestAdapterBomDTO dto) {

        // 生成Basic认证字符串
        String username = IpAddressConstant.USER_CS;
        String password = IpAddressConstant.PASSWORD_CS;
        String auth = username + ":" + password;
        String base64Auth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        String authHeader = "Basic " + base64Auth;

        String body = HttpRequest.post(IpAddressConstant.SAP_CS_BOMDR)
                .header("Content-Type", "application/json")
                .header("Authorization", authHeader)  // 添加Basic认证头
                .body(JSONUtil.toJsonStr(dto))
                .execute()
                .body();

        RestAdapterBomDTO restAdapterDTO = JSONUtil.toBean(body, RestAdapterBomDTO.class);

        return restAdapterDTO;
    }

    @Override
    public RestAdapterEsReturDTO restAdapterQas(RestAdapterQasDTO dto) {

        // 生成Basic认证字符串
        String username = IpAddressConstant.USER_CS;
        String password = IpAddressConstant.PASSWORD_CS;
        String auth = username + ":" + password;
        String base64Auth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        String authHeader = "Basic " + base64Auth;

        String body = HttpRequest.post(IpAddressConstant.SAP_CS_QAS)
                .header("Content-Type", "application/json")
                .header("Authorization", authHeader)  // 添加Basic认证头
                .body(JSONUtil.toJsonStr(dto))
                .execute()
                .body();
        RestAdapterEsReturDTO restAdapterEsReturDTO = JSONUtil.toBean(body, RestAdapterEsReturDTO.class);
        return restAdapterEsReturDTO;
    }

    @Override
    public SapRespAdapterSreqDTO getSuppliersByMaterial(SapRestAdapterSreqDTO.InTab inTab) {

        SapRestAdapterSreqDTO dto = new SapRestAdapterSreqDTO();
        dto.setIT_TAB(inTab);

        // 生成Basic认证字符串
        String username = IpAddressConstant.USER_CS;
        String password = IpAddressConstant.PASSWORD_CS;
        String auth = username + ":" + password;
        String base64Auth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        String authHeader = "Basic " + base64Auth;

        String body = HttpRequest.post(IpAddressConstant.SAP_CS_GYS)
                .header("Content-Type", "application/json")
                .header("Authorization", authHeader)  // 添加Basic认证头
                .body(JSONUtil.toJsonStr(dto))
                .execute()
                .body();
        SapRespAdapterSreqDTO restAdapterEsReturDTO = JSONUtil.toBean(body, SapRespAdapterSreqDTO.class);
        return restAdapterEsReturDTO;
    }

}
